﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoCreateCodePlus;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common;
using XKPlatform.Common.Enums;
using XKPlatform.DataModels;
using XKPlatform.DataModels.Dao.BaseDao;
using XKPlatform.DataModels.Dao.BaseEntity;
using XKPlatform.DataModels.ParamsModel;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.DataModels.SysModel;
using XKPlatform.IService;

namespace XKPlatform.Controllers.SysController
{

    [Route("[controller]/[action]")]
    public class SysAutoCreateCodeCfgController : BaseController
    {
        private readonly IHttpContextAccessor _IHttpContextAccessor;
        private readonly ISysTableColCfgService _itableColService;
        private readonly ISysAutoCodeTableCfgService _iautoCodeService;
        private readonly AutoCodeClass _autoCode; 

        public SysAutoCreateCodeCfgController(AutoCodeClass autoCreateCodeService,  
            ISysTableColCfgService tableColC, ISysAutoCodeTableCfgService autoCodeService, IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor)
        {
            _IHttpContextAccessor = httpContextAccessor;
            _itableColService = tableColC;
            _iautoCodeService = autoCodeService;
            _autoCode = autoCreateCodeService;  
        }

        /// <summary>
        /// 查询可以自动生成代码文件的表名信息
        /// </summary>
        /// <param name="tble"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetList([FromBody] AutoCreataCodeParams tble)
        {
            PageInfo pageinfo = new PageInfo();
            pageinfo.PageIndex = tble.Page;
            pageinfo.PageSize = tble.Limit;
            pageinfo.IsPaging = true;
            long count = 0;

            List<SortInfo<SysAutoCodeTableCfg, object>> sorLst = new List<SortInfo<SysAutoCodeTableCfg, object>>();
            SortInfo<SysAutoCodeTableCfg, object> sorItem = new SortInfo<SysAutoCodeTableCfg, object>();
            sorItem.Orderby = o => o.createBy;
            sorItem.SortMethods = SortEnum.Desc;
            sorLst.Add(sorItem);
            Expression<Func<SysAutoCodeTableCfg, bool>> where = o => 1 == 1;

            if (!string.IsNullOrWhiteSpace(tble.tbDes))
            {
                where = where.And(o => o.tbDes == tble.tbDes);

            }
            if (!string.IsNullOrWhiteSpace(tble.tbModelName))
            {
                where = where.And(o => o.tbModelName == tble.tbModelName);
            }
            if (!string.IsNullOrWhiteSpace(tble.tbName))
            {
                where = where.And(o => o.tbName == tble.tbName);
            }

            var ret = _iautoCodeService.GetList(where, sorLst, pageinfo);
            count = ret.count;
            var list = ret.list;

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = list, count = Convert.ToInt32(count) });


        }
        /// <summary>
        /// 导入配置信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ImportData()
        {

            SysUser userInfos = SSOClient.getUser(HttpContext);
            if (userInfos.UserID == Guid.Empty)
            {
                return Json(new { code = (int)MsgCodeEnum.InvalidParameter, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.InvalidParameter) });
            }
            var file = Request.Form.Files[0];

            if (file == null)
            {
                return Json(new BaseModel { code = (int)MsgCodeEnum.InvalidParameter, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.InvalidParameter) });
            }

            IList<string> list = new List<string>() { ".xlsx", ".xls" };
            if (!list.Contains(Path.GetExtension(file.FileName)))
            {
                return Json(new BaseModel { code = (int)MsgCodeEnum.InvalidParameter, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.InvalidParameter) });
            }
            //开始导入数据
            DataTable dataTable = ExcelHelper.ReadExcel(file.OpenReadStream(), true);

            if (dataTable == null || dataTable.Rows.Count == 0)
            {
                throw new Exception("数据文件为空！");
            }
            List<SysTableColCfg> colList = new List<SysTableColCfg>();
            SysTableColCfg colCfg = new SysTableColCfg();
            var dtNow = DateTime.Now;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                colCfg.Id = Guid.NewGuid().ToString();
                colCfg.tbName = dataTable.Rows[i][5]?.ToString();
                colCfg.colName = dataTable.Rows[i][0]?.ToString();
                colCfg.colDes = dataTable.Rows[i][2]?.ToString();
                colCfg.colType = dataTable.Rows[i][1]?.ToString();
                colCfg.netType = dataTable.Rows[i][4]?.ToString();
                colCfg.isInsert = true;
                colCfg.isEdit = true;
                colCfg.isList = true;
                colCfg.isSearch = true;
                colCfg.biTian = true;
                colCfg.viewName = dataTable.Rows[i][7]?.ToString();
                colCfg.isCreateSingleFile = dataTable.Rows[i][6].ObjectToBoolean();
                colCfg.isCreateTable = dataTable.Rows[i][8].ObjectToBoolean();
                colCfg.createBy = userInfo.UserName;
                colCfg.createOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                colList.Add(colCfg);
            }
            // int count = SqlHelper.BatchInsert(dt, "ExamBank", dt.Rows.Count, DbHelper.MainDB_ConnectString);



            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = "" });
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="tble"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveOrEdit([FromBody] SysAutoCodeTableCfg tble)
        {
            tble.createOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            tble.createBy = userInfo.UserName;

            BaseFreeSqlDao<SysPageButtonInfoCfg> pageBtnDao = new BaseFreeSqlDao<SysPageButtonInfoCfg>();



            if (string.IsNullOrWhiteSpace(tble.Id))
            {
                tble.Id = Guid.NewGuid().ToString();
                //增加列信息 清楚已存在信息
                _itableColService.Delete(o => o.tbName == tble.tbName);
                string sql = string.Format(@"insert into [dbo].[SysTableColCfg] (Id,tbName,colName,colType,isInsert,isEdit,isList,biTian,netType)
select NEWID(),'{0}', c.name as cname ,p.name as dtype ,1,1,1,1,
case  p.name when 'text' then 'string'
 when 'varchar' then 'string'
  when 'char' then 'string'
   when 'nvarchar' then 'string'
   when 'nchar' then 'string'
   when 'ntext' then 'string'
   when 'uniqueidentifier' then 'string'
   when 'int' then 'int'
   when 'smallint' then 'Int16'
   when 'tinyint' then 'byte'
   when 'bigint' then 'long'
   when 'bit' then 'bool?'
   when 'money' then 'decimal'
   when 'smallmoney' then 'decimal'
   when 'numeric' then 'decimal'
   when 'decimal' then 'decimal'
   when 'datetime' then 'DateTime?'
   when 'smalldatetime' then 'DateTime?'
   when 'timestamp' then 'DateTime?'
   when 'datetime2' then 'DateTime?'
   when 'real' then 'Single'
   when 'float' then 'double'
   when 'image' then 'byte[]'
   when 'binary' then 'byte[]'
   when 'varbinary' then 'byte[]'
	    
else 'string' end
from sys.columns c,sys.objects t, sys.types p where t.name = '{0}' and t.is_ms_shipped = 0 and c.[object_id]= t.[object_id] and p.user_type_id = c.user_type_id", tble.tbName);

                Common.SqlHelper.ExecuteSql(sql);
                _iautoCodeService.AddModel(tble);
            }
            else
            {   //删除页面按钮配置信息
                pageBtnDao.Delete(o => o.TableID == tble.Id);

                _iautoCodeService.UpdateModel(tble, o => o.Id == tble.Id);
            }
            //页面按钮配置信息
            if (tble.BtnActionLst != null && tble.BtnActionLst.Count > 0)
            {
                List<SysPageButtonInfoCfg> lst = new List<SysPageButtonInfoCfg>();
                foreach (var item in tble.BtnActionLst)
                {
                    SysPageButtonInfoCfg pageBtn = new SysPageButtonInfoCfg();
                    pageBtn.ID = Guid.NewGuid().ToString();
                    pageBtn.TableID = tble.Id;
                    pageBtn.ButtonId = item.BtnName;
                    pageBtn.IsPermission = item.IsPermission;
                    pageBtn.ActionUrl = string.Format("/{0}/{1}", tble.tbName, item.BtnName);
                    pageBtn.CreatedBy = userInfo.UserName;
                    pageBtn.CreatedOn = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    lst.Add(pageBtn);
                }
                pageBtnDao.BatchInsert(lst);
            }

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Delete(string id)
        {
            var itme = _iautoCodeService.GetModel(o => o.Id == id);
            if (itme == null)
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Failed, msg = "没找到要删除的数据" });

            }
            //删除表配置
            _iautoCodeService.Delete(o => o.Id == id);
            //删除列配置
            _itableColService.Delete(o => o.tbName == itme.tbName);
            //删除页面按钮信息
            BaseFreeSqlDao<SysPageButtonInfoCfg> pageBtnDao = new BaseFreeSqlDao<SysPageButtonInfoCfg>();
            pageBtnDao.Delete(o => o.TableID == id);
            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });

        }

        /// <summary>
        /// 生成代码 后台   页面 todo
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult AutoCreateCode(string id)
        {

            string url = "";
            var model = _iautoCodeService.GetModel(o => o.Id == id);
            if (model == null)
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Failed, msg = "请确认表配置信息是否存在" });
            }

            var dic = DateTime.Now.ToString("yyyyMMddHHmmss");
            HttpContextCore.filePath = Path.Combine(HttpContextCore.Env.WebRootPath, model.tbModelName + dic);
            var ret = _itableColService.GetList(o => o.tbName == model.tbName);

            var path = _autoCode.CreateCode(model.tbName, model.tbModelName, HttpContextCore.filePath, HttpContextCore.ConnectionStrings, ret.list);

            _iautoCodeService.SaveButtonInfo(id, model.tbName);
            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = "/" + model.tbModelName + dic + "/" + model.tbModelName + ".zip" });
        }
        /// <summary>
        /// 获取列配置
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetColList(string Id)
        {
            var tableModel = _iautoCodeService.GetModel(o => o.Id == Id);
            var ret = _itableColService.GetList(o => o.tbName == tableModel.tbName);
         
            return Json(new { code = (int)MsgCodeEnum.Success, msg = "", data = ret.list, count = Convert.ToInt32(ret.list.Count) });

        }
        /// <summary>
        /// 获取列配置
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetTableColList(string tableName)
        {
            var ret = _itableColService.GetList(o => o.tbName == tableName);
            var hasSearch = ret.list.Where(o => o.isSearch).ToList().Count > 0;
            return Json(new { code = (int)MsgCodeEnum.Success, msg = "", data = ret.list, hasSearch = hasSearch });

        }
        /// <summary>
        /// 保存列配置
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveColConfig([FromBody] List<SysTableColCfg> list)
        {
            if (list == null || list.Count == 0)
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Failed, msg = "提交数据为空" });
            }

            for (var index = 0; index < list.Count; index++)
            {
                if (string.IsNullOrEmpty(list[index].Id))
                {
                    list[index].Id = Guid.NewGuid().ToString();
                }
            }
            _itableColService.Delete(o => o.tbName == list[0].tbName);
            _itableColService.BatchSave(list);
            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
        }
    }
}
